import { createSlice, createAsyncThunk, PayloadAction } from "@reduxjs/toolkit";
import { authUserLogin } from "../../api";
import { Ajax } from "../../Utils/AjaxConfig";
interface UserState {
  loading: boolean;
  error: string | null;
  token: string | null;
}

interface ParamsProps {
  email: string;
  password: string;
}

const initialState: UserState = {
  loading: false,
  error: null,
  token: "",
};

export const userProduct = createAsyncThunk(
  "userProduct/singIn",
  async (params: ParamsProps, thunkAPI) => {
    const { data } = await Ajax.post(`${authUserLogin}`, {
      email: params.email,
      password: params.password,
    });
    return data.token;
  }
);

export const userSlice = createSlice({
  name: "user",
  initialState,
  reducers: {
    logOut: (state)=>{
      state.token = null;
      state.error = null;
      state.loading = false;
    }
  },
  extraReducers: {
    [userProduct.pending.type]: (state, action) => {
      state.loading = true;
    },
    [userProduct.fulfilled.type]: (
      state,
      action: PayloadAction<string | null>
    ) => {
      state.loading = false;
      state.error = null;
      state.token = action.payload;
    },
    [userProduct.rejected.type]: (
      state,
      action: PayloadAction<string | null>
    ) => {
      state.loading = false;
      state.error = action.payload;
    },
  },
});
